package com.java.basis.thread.cas;

import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author wangning
 * @create 2022-01-29 15:27
 */
public class TestUnsafe {
	public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
		//Unsafe对象不能直接创建，需要调用反射的方法创建
		Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
		//设置允许访问私有成员变量
		theUnsafe.setAccessible(true);

		Unsafe unsafe = (Unsafe) theUnsafe.get(null);
		System.out.println(unsafe);

		//1.获取域的偏移地址
		long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
		long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));

		Teacher t = new Teacher();
		//2.执行CAS操作
		unsafe.compareAndSwapInt(t, idOffset, 0, 1);
		unsafe.compareAndSwapObject(t, nameOffset, null, "张三");
		System.out.println(t.toString());

	}
}

@Data
class Teacher {
	volatile int id;
	volatile String name;
}
